package com.yunti.yntk.activity.stuManage;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.yunti.yntk.R;
import com.yunti.yntk.activity.BaseActivity;
import com.yunti.yntk.anotation.ViewInject;
import com.yunti.yntk.api.Result;
import com.yunti.yntk.db.AppDatabase;
import com.yunti.yntk.db.ExamStuDao;
import com.yunti.yntk.manager.ConfigManager;
import com.yunti.yntk.manager.NetWorkManager;
import com.yunti.yntk.db.po.ExamStu;
import com.yunti.yntk.util.BitmapUtils;
import com.yunti.yntk.util.FileUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class StuManageActivity extends BaseActivity {

    @ViewInject(R.id.stuListView)
    private ListView stuListView;

    @ViewInject(R.id.importButton)
    private TextView importButton;


    private List<ExamStu> examStuArrayList = new ArrayList<>();

    private YnStuAdapter ynStuAdapter;

    private ExamStuDao examStuDao;

    @Override
    public int initLayoutId() {
        return R.layout.activity_stumanage;
    }

    @Override
    public void initView() {

        ynStuAdapter = new YnStuAdapter(this, R.layout.item_szstuitemlist, examStuArrayList);
        stuListView.setAdapter(ynStuAdapter);

        examStuDao = AppDatabase.getDatabase(getBaseContext()).examStuDao();

        importButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(StuManageActivity.this);
                builder.setTitle("导入考生")
                        .setPlaceholder("在此输入批次号")
                        .setInputType(InputType.TYPE_CLASS_TEXT)
                        .addAction("取消", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                dialog.dismiss();
                            }
                        })
                        .addAction("确定", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                CharSequence text = builder.getEditText().getText();
                                if (text != null && text.length() > 0) {
                                    dialog.dismiss();
                                    importSzStu(text.toString());
                                } else {
                                    Toast.makeText(getBaseContext(), "在此输入批次号", Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                        .show();
            }
        });


    }

    private void importSzStu(String kklc) {
        ExamStu examStuReq = new ExamStu();
        examStuReq.setBatchName(kklc);
        Call<Result<List<ExamStu>>> call = NetWorkManager.getRequest().getListByBatch(examStuReq);
        call.enqueue(new Callback<Result<List<ExamStu>>>() {
            @Override
            public void onResponse(Call<Result<List<ExamStu>>> call, Response<Result<List<ExamStu>>> response) {
                Result<List<ExamStu>> result = response.body();
                if (result.getCode() == 200) {
                    List<ExamStu> localExamStuList = result.getData();
                    System.out.println(localExamStuList.size());
                    new Thread(() -> {
                        examStuDao.deleteAll();
                        for (int i = 0; i < localExamStuList.size(); i++) {
                            Bitmap bitmap = BitmapUtils.getBitmapByurl(ConfigManager.getInstance().getApiAddress() + localExamStuList.get(i).getPhoto());
                            String picName = localExamStuList.get(i).getExamNum() + ".jpg";
                            // 保存图片到新目录中
                            File facePicDir = FileUtils.getBatchImportSuccessDirectory(getBaseContext());
                            if (facePicDir != null) {
                                File savePicPath = new File(facePicDir, picName);
                                if (FileUtils.saveBitmap(savePicPath, bitmap)) {
                                    localExamStuList.get(i).setPhoto(savePicPath.getPath());
                                } else {
                                    localExamStuList.get(i).setPhoto(null);
                                }
                            }
                            examStuDao.insertAll(localExamStuList.get(i));
                        }
                    }).start();
                } else {

                }

            }

            @Override
            public void onFailure(Call<Result<List<ExamStu>>> call, Throwable t) {

            }
        });
    }


    private void getYnStu() {
        new Thread(() -> {
            examStuArrayList.addAll(examStuDao.getAll());
            runOnUiThread(() -> {
                ynStuAdapter.notifyDataSetChanged();
            });
            System.out.println(examStuArrayList);
        }).start();
    }

    @Override
    public void initData() throws IOException {
        examStuDao = AppDatabase.getDatabase(getBaseContext()).examStuDao();
        getYnStu();
    }

    class YnStuAdapter extends ArrayAdapter<ExamStu> {

        public YnStuAdapter(@NonNull Context context, int resource, @NonNull List<ExamStu> objects) {
            super(context, resource, objects);
        }

        //每个子项被滚动到屏幕内的时候会被调用
        @SuppressLint("SetTextI18n")
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            ExamStu ynStu = getItem(position);//得到当前项的 Fruit 实例
            //为每一个子项加载设定的布局
            View view = LayoutInflater.from(getContext()).inflate(R.layout.item_szstuitemlist, parent, false);
            //分别获取 image view 和 textview 的实例
            ImageView photo = view.findViewById(R.id.photo);

            TextView no = view.findViewById(R.id.no);
            TextView name = view.findViewById(R.id.name);

            TextView sex = view.findViewById(R.id.sex);

            TextView tyzb = view.findViewById(R.id.tyzb);
            TextView tyxh = view.findViewById(R.id.tyxh);

            TextView qqzb = view.findViewById(R.id.qqzb);
            TextView qqxh = view.findViewById(R.id.qqxh);

            no.setText(ynStu.getExamNum());
            name.setText(ynStu.getStuName());
            if (ynStu.getSex() != null) {
                sex.setText(ynStu.getSex().equals(1) ? "男" : "女");
            }

//            tyzb.setText(ynStu.getTyzb());
//            tyxh.setText(ynStu.getTyxh());
//
//            qqzb.setText(ynStu.getQqzb());
//            qqxh.setText(ynStu.getQqxh());

            new Thread(() -> {
                if (ynStu.getPhoto() == null || ynStu.getPhoto().trim().equals("")) {
                    if (ynStu.getSex() == null || (ynStu.getSex() != null && ynStu.getSex().equals(1))) {
                        runOnUiThread(() -> {
                            photo.setImageResource(R.mipmap.boy);
                        });
                    } else if (ynStu.getSex() != null && ynStu.getSex().equals(2)) {
                        runOnUiThread(() -> {
                            photo.setImageResource(R.mipmap.girl);
                        });
                    }
                } else {
                    Bitmap bitmap = BitmapUtils.getBitmapByurl(ConfigManager.getInstance().getApiAddress() + ynStu.getPhoto());
                    Bitmap descBmp = BitmapUtils.calculateInSampleSize(bitmap, 100, 100);
                    runOnUiThread(() -> {
                        if (descBmp != null) {
                            photo.setImageBitmap(descBmp);
                        } else {
                            if (ynStu.getSex() == null || (ynStu.getSex() != null && ynStu.getSex().equals("1"))) {
                                runOnUiThread(() -> {
                                    photo.setImageResource(R.mipmap.boy);
                                });
                            } else if (ynStu.getSex() != null && ynStu.getSex().equals("2")) {
                                runOnUiThread(() -> {
                                    photo.setImageResource(R.mipmap.girl);
                                });
                            }
                        }
                    });
                }

            }).start();
            return view;
        }
    }
}
